package com.yanze.schoolinformation.view.home;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.yanze.schoolinformation.R;
import com.yanze.schoolinformation.adapter.rv.HomeNewsAdapter;
import com.yanze.schoolinformation.adapter.vp.CommonViewPagerAdapter;
import com.yanze.schoolinformation.adapter.vp.ViewPagerHolder;
import com.yanze.schoolinformation.adapter.vp.ViewPagerHolderCreator;
import com.yanze.schoolinformation.app.C;
import com.yanze.schoolinformation.base.BaseFragment;
import com.yanze.schoolinformation.databinding.FragmentHomeBinding;
import com.yanze.schoolinformation.databinding.HeaderHomeHeadBinding;
import com.yanze.schoolinformation.model.bean.HomeBanner;
import com.yanze.schoolinformation.model.bean.NewsModule;
import com.yanze.schoolinformation.model.bean.resp.RespHomeBanner;
import com.yanze.schoolinformation.utils.PerfectClickListener;
import com.yanze.schoolinformation.utils.ToastUtils;
import com.yanze.schoolinformation.view.home.news.SchoolNewsActivity;
import com.yanze.schoolinformation.view.webview.WebViewActivity;
import com.yanze.schoolinformation.viewModule.HomeViewModule;
import com.yanze.schoolinformation.viewModule.school_news.HomeNavigator;


import java.util.ArrayList;
import java.util.List;

import static com.yanze.schoolinformation.viewModule.HomeViewModule.getTodayTime;


/**
 * 首页
 * Created by MrZheng on 2018/3/14.
 */

public class HomeFragment extends BaseFragment<FragmentHomeBinding> implements HomeNavigator {
    private HomeNewsAdapter mAdapter;
    private HeaderHomeHeadBinding mHeaderBinding;
    private boolean mIsPrepared = false;
    private boolean mIsFirst = true;
    private boolean mIsgetBannerSuccess = false;
    private boolean mIsgetNewsSuccess = false;
    private RotateAnimation animation;
    private HomeViewModule viewModule;


    @Override
    public int setContent() {
        return R.layout.fragment_home;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        showContentView();
        //初始化动画
        initAnimation();

        //HomeViewModule
        viewModule = new HomeViewModule(this, this);

        //头布局
        mHeaderBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.header_home_head, null, false);
        initLocalSetting();
        initRecyclerView();
        mIsPrepared = true;

        loadData();
    }

    private void initAnimation() {
        bindingView.llLoading.setVisibility(View.VISIBLE);
        animation = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(3000);//设置动画持续时间
        animation.setInterpolator(new LinearInterpolator());//不停顿
        animation.setRepeatCount(10);
        bindingView.ivLoading.setAnimation(animation);
        animation.startNow();
    }

    @Override
    protected void loadData() {
        if (!mIsVisible || !mIsPrepared || !mIsFirst) {
            return;
        }
        mIsFirst = false;
        viewModule.getXuHaiData();
    }

    private void initRecyclerView() {
        bindingView.xrvHome.setPullRefreshEnabled(false);
        bindingView.xrvHome.setLoadingMoreEnabled(false);
        bindingView.xrvHome.addHeaderView(mHeaderBinding.getRoot());
        bindingView.xrvHome.setLayoutManager(new LinearLayoutManager(getContext()));

        // 需加，不然滑动不流畅
        bindingView.xrvHome.setNestedScrollingEnabled(false);
        bindingView.xrvHome.setHasFixedSize(false);
        bindingView.xrvHome.setItemAnimator(new DefaultItemAnimator());

        mAdapter = new HomeNewsAdapter(getContext());
        bindingView.xrvHome.setAdapter(mAdapter);
    }

    /**
     * 设置本地数据点击事件等
     */
    private void initLocalSetting() {
        // 显示日期,去掉第一位的"0"
        mHeaderBinding.includeEveryday.tvDailyText.setText(getTodayTime().get(2).indexOf("0") == 0 ?
                getTodayTime().get(2).replace("0", "") : getTodayTime().get(2));
        mHeaderBinding.includeEveryday.ibXiandu.setOnClickListener(listener);
        mHeaderBinding.includeEveryday.ibWanAndroid.setOnClickListener(listener);
        mHeaderBinding.includeEveryday.ibMovieHot.setOnClickListener(listener);
        mHeaderBinding.includeEveryday.flEveryday.setOnClickListener(listener);
        viewModule.getBanner();
    }

    private PerfectClickListener listener = new PerfectClickListener() {
        @Override
        protected void onNoDoubleClick(View v) {
            switch (v.getId()) {
                case R.id.ib_xiandu:
                    WebViewActivity.loadUrl(v.getContext(), C.url.School_Synopsis, "学院概况");
                    break;
                case R.id.ib_wan_android:
                    WebViewActivity.loadUrl(v.getContext(), C.url.Employment_Guidance, "就业指导");
                    break;
                case R.id.ib_movie_hot:
                    WebViewActivity.loadUrl(v.getContext(), C.url.Public_Service, "公共服务");
                    break;
                case R.id.fl_everyday:
                    WebViewActivity.loadUrl(v.getContext(), C.url.Deans_Office_1, "教务处");
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void getBannerSuccess(final List<HomeBanner> banners) {
        //为banner设置数据
        mHeaderBinding.banner.setVisibility(View.VISIBLE);
        mHeaderBinding.banner.setPage(banners, new ViewPagerHolderCreator() {
            @Override
            public ViewPagerHolder createViewHolder() {
                return new ImageViewHolder();
            }
        }, new CommonViewPagerAdapter.BannerPageClickListener() {
            @Override
            public void onPageClick(View view, int position) {
                WebViewActivity.loadUrl(getContext(), banners.get(position).getLink(), "正在加载...");
            }
        });
        mHeaderBinding.banner.start();
        mIsgetBannerSuccess = true;
        if (mIsgetBannerSuccess && mIsgetNewsSuccess) {
            showRotaLoading(false);
        }
    }

    @Override
    public void getBannerFaild() {
        mHeaderBinding.banner.setVisibility(View.GONE);
        showError();
        mIsgetBannerSuccess = false;
    }

    @Override
    public void getNewsSuccess(final List<NewsModule> news) {
        mAdapter.clear();
        mAdapter.addAll(news);
        mAdapter.notifyDataSetChanged();

        mIsgetNewsSuccess = true;
        if (mIsgetBannerSuccess && mIsgetNewsSuccess) {
            showRotaLoading(false);
        }
    }

    @Override
    public void getNewsFaild() {
        showError();
        mIsgetNewsSuccess = false;
    }

    @Override
    public void showSuccessContint() {
        showContentView();
    }

    @Override
    public void onRefresh() {
        showContentView();
        showRotaLoading(true);
        mIsFirst = true;
        viewModule.getBanner();
        loadData();
    }

    /**
     * Banner图回调
     */
    public class ImageViewHolder implements ViewPagerHolder<HomeBanner> {
        private ImageView mImageView;

        @Override
        public View createView(Context context) {
            mImageView = new ImageView(context);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            mImageView.setLayoutParams(params);
            mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return mImageView;
        }

        @Override
        public void bindView(Context context, int position, HomeBanner data) {
            Glide.with(context)
                    .load(data.getImage())
                    .placeholder(R.drawable.img_two_bi_one)
                    .error(R.drawable.img_two_bi_one)
                    .crossFade(1500)
                    .into(mImageView);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mHeaderBinding != null && mHeaderBinding.banner != null) {
            mHeaderBinding.banner.start();
        }
        //失去焦点，否则RecyclerView第一个item会回到顶部
        bindingView.xrvHome.setFocusable(false);
        //开始图片请求
        Glide.with(getActivity()).resumeRequests();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mHeaderBinding != null && mHeaderBinding.banner != null) {
            mHeaderBinding.banner.pause();
        }
        // 停止全部图片请求 跟随着Activity
        Glide.with(getActivity()).pauseRequests();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        viewModule.onDestory();
    }

    /**
     * 显示旋转动画
     */
    private void showRotaLoading(boolean isLoading) {
        if (isLoading) {
            bindingView.llLoading.setVisibility(View.VISIBLE);
            bindingView.xrvHome.setVisibility(View.GONE);
            animation.startNow();
        } else {
            bindingView.llLoading.setVisibility(View.GONE);
            bindingView.xrvHome.setVisibility(View.VISIBLE);
            animation.cancel();
        }
    }
}
